package com.flyduck.security;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyduck.entity.SysUser;
import com.flyduck.manager.SysPermissionCacheManager;
import com.flyduck.manager.SysPermissionManager;
import com.flyduck.mapper.SysUserMapper;
import com.flyduck.utils.JwtUtils;
import com.flyduck.utils.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: vue-admin-java
 * @description: 其他请求携带token，这里解析token完成自动登录
 * @author: flyduck
 * @create: 2024-05-28 21:45
 **/
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private SysPermissionCacheManager sysPermissionCacheManager;

    @Autowired
    private SysUserMapper sysUserMapper;

    public TokenAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader(jwtUtils.getHeader());
        //没有token，直接跳过
        if (StringUtils.isBlank(token)) {
            chain.doFilter(request,response);
            return;
        }

        //有token，解析
        Claims claims = jwtUtils.getClaimsByToken(token);
        if (claims == null) {
            throw new JwtException("token异常");
        }
        if(jwtUtils.isTokenExpired(claims)){
            throw new JwtException("token已过期");
        }

        String username = claims.getSubject();

        SysUser sysUser = sysUserMapper.selectOne(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUsername, username)
        );

        List<String> permissionList = sysPermissionCacheManager.getPermissionListByUserId(sysUser.getId());
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(permissionList)){
            authorityList = permissionList.stream()
                    .map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
        }


        //获取用户的权限等信息
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null,authorityList);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        chain.doFilter(request,response);
    }
}
